package ch.fusun.baron.unit.ui;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.data.DataListener;
import ch.fusun.baron.data.DataUpdate;
import ch.fusun.baron.map.Tile;
import ch.fusun.baron.map.ui.gef.editpart.TileChild;
import ch.fusun.baron.map.ui.gef.editpart.TileChildrenProvider;
import ch.fusun.baron.player.Dynasty;
import ch.fusun.baron.property.api.PropertyService;
import ch.fusun.baron.unit.Unit;
import ch.fusun.baron.unit.service.UnitService;

/**
 * Adds a little flag to the city, corresponding to the coat of arms of the
 * dynasty
 */
public class UnitDynastyTileChildrenProvider implements TileChildrenProvider {

	private final List<DataListener> listeners = new LinkedList<DataListener>();
	private transient UnitService unitService;
	@Inject
	private transient PropertyService propertyService;

	/**
	 * Injection constructor
	 */
	public UnitDynastyTileChildrenProvider() {
	}

	/**
	 * @param cityService
	 *            The injected service
	 */
	@Inject
	public void setCityService(UnitService cityService) {
		this.unitService = cityService;
		this.unitService.addDataListener(this);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Collection<TileChild> getChildren(Tile model) {
		Collection<Unit> units = unitService.getUnits(model);
		Collection<TileChild> children = new ArrayList<TileChild>();
		if (units != null && !units.isEmpty()) {
			Unit unit = units.iterator().next();
			Dynasty dynasty = (Dynasty) propertyService.getOwnership(unit);
			if (unit != null) {
				children.add(new UnitDynastyTileChild(dynasty));
			}
		}
		return children;
	}

	@Override
	public void addListener(DataListener listener) {
		this.listeners.add(listener);
	}

	@Override
	public void dataChanged(DataUpdate update) {
		for (DataListener listener : listeners) {
			listener.dataChanged(update);
		}
	}

}
